﻿<%@ WebHandler Language="C#" Class="EmployeeOprLogs" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Data;
using System.Text;
using System.Data.SqlClient;

public class EmployeeOprLogs : AjaxHandlerBase
{
 
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        if (!string.IsNullOrEmpty(context.Request.Params["op"]))
        {
            //处理类型
            string strOperate = context.Request.Params["op"];

            switch (strOperate.Trim())
            {
                case "Search":
                    SearchEmployeeOprLogs(context);
                    break;
                case "GetOprTypeComboList":
                    GetOprTypeComboList(context);
                    break;
                default:
                    break;
            }
        }
    }

    /// <summary>
    /// 查询数据库返回相关分页DataSet表生成Table返回
    /// </summary>
    /// <param name="context"></param>
    /// <param name="strWhere"></param>
    public void GetEmployeeOprLogs(HttpContext context, string strWhere)
    {
        try
        {
            int count = 0;
            Constants.Pagination stuPg = new Constants.Pagination();

            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            //排序
            string strOrderField = "Addtime desc";

            //欲选择字段列表 
            string FieldList = "RecordId,Id,UserId,UserName,DepartId,DepartName,OprType,OperationContext,Addtime ";
            //子查询欲选择字段列表
            string TableFieldList = "RecordId,Id,UserId,UserName,DepartId,DepartName,OprType,OperationContext,Addtime";

            //所要查询的表名
            string TableName = "House_UserLogs";
            //根据sql执行查询
            DataSet ds = Chenxin.Lib.House.DAL.House_UserLogs.GetList(strPageSize, strPageIndex, strOrderField, TableName, strWhere, FieldList, TableFieldList, true);
            //数据量
            count = (int)ds.Tables[1].Rows[0][0];

            string strHtml = string.Empty;

            if (!GetEmployeeOprLogsHtml(ds, out strHtml))
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "生成HTML错误", ""));
            }
            stuPg.count = count;
            stuPg.data = strHtml.ToString();
            
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "OK", stuPg));

        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    /// <summary>
    /// 生成一个用户操作日志Table返回
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetEmployeeOprLogsHtml(DataSet dslist, out string strHtml)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<table width=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        sb.Append("<th width=\"10%\">查询人</th>");
        sb.Append("<th width=\"10%\">所在门店</th>");
        sb.Append("<th width=\"15%\">查询时间</th>");
        sb.Append("<th width=\"10%\">类型</th>");
        sb.Append("<th width=\"55%\">日志内容</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");

        foreach (DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\" >", row["RecordId"].ToString());

            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UserName", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DepartName", ""));
            sb.AppendFormat("<td>{0:yyyy-mm-dd hh-mm-ss}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Addtime", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprType", ""));

            if (row["OperationContext"].ToString().Length > 40)
            {
                sb.AppendFormat("<td title=\"{0}\">{1}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OperationContext", ""),row["OperationContext"].ToString().Substring(0, 38) + "...");
            }
            else
            {
                sb.AppendFormat("<td title=\"{0}\">{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OperationContext", ""));
            }
            sb.Append("</tr>");
        }

        sb.Append("</tbody></table>");

        strHtml = sb.ToString();
        return true;
    }

    /// <summary>
    /// 查询用户操作日志
    /// </summary>
    /// <param name="context"></param>
    public void SearchEmployeeOprLogs(HttpContext context)
    {
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
        Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

        //判断权限范围/////////////////////////////////////////////
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (employee != Guid.Empty)
            sb.AppendFormat(" AND (UserId = '{0}') ", employee);
        else if (departs != Guid.Empty)
            sb.AppendFormat(" AND (DepartId = '{0}')", departs);
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null)
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失"));
                return;
            }
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (House_UserLogs.DepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
        }
        else if (company != Guid.Empty)
        {
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (House_UserLogs.DepartId = M.Departid AND M.CompanyId='{0}'))) ", company);
        }
        else if (city != Guid.Empty)
        {
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (House_UserLogs.DepartId = M.Departid AND M.CityId='{0}'))) ", city);
        }
        else
            sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", CurrentUserInfo.CompanyId);

        System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
        
        sb1.Append(" Addtime > dateadd(day,-90,getdate()) ");
        //查看所有操作日志权限
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_OprTypeLog_All))
        {
            
        }
        //查看城市操作日志权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_OprTypeLog_City))
        {
            sb1.Append("and (EXISTS(");
            sb1.Append("Select 1 from v_Hr_User_BaseInfo M ");
            sb1.AppendFormat("WHERE (House_UserLogs.UserId = M.Userid AND  M.CityId= '{0}'))) ", CurrentUserInfo.CityId);
        }
        //查看公司操作日志权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_OprTypeLog_Company))
        {
            sb1.Append("and (EXISTS(");
            sb1.Append("Select 1 from v_Hr_User_BaseInfo M ");
            sb1.AppendFormat("WHERE (House_UserLogs.UserId = M.Userid AND  M.CompanyId= '{0}'))) ", CurrentUserInfo.CompanyId);
        }
        //查看部门操作日志权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_OprTypeLog_Department))
        {
            sb1.Append("and (EXISTS(");
            sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
            sb1.AppendFormat("WHERE (House_UserLogs.DepartId = M.Departid AND  M.Userid= '{0}' and M.ViewUserLog = 1))) ", CurrentUserInfo.UserId);
        }
        else
        {
            sb1.Append("and (EXISTS(");
            sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
            sb1.AppendFormat("WHERE (House_UserLogs.UserId = '{0}' and M.ViewUserLog = 1))) ", CurrentUserInfo.UserId);
            //sb1.AppendFormat("and (UserId = '{0}')", CurrentUserInfo.UserId);
        }

        if (!String.IsNullOrEmpty(sb.ToString()))
            sb1.Append(sb.ToString());

        string addtime = context.Request.Params["Addtime"];//查看时间
        string oprtype = context.Request.Params["OprType"];//类型

        if (!String.IsNullOrEmpty(addtime))
        {
            sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,Addtime,120)),120) >= '{0}'", (addtime)));
        }
        if (!String.IsNullOrEmpty(oprtype))
        {
            sb1.Append(" and OprType like '%" + oprtype + "%'");
        }

        //根据查询条件返回生成一个用户操作日志Table
        GetEmployeeOprLogs(context, sb1.ToString());
    }

    /// <summary>
    /// 获取用户操作日志类型Combo列表
    /// </summary>
    /// <param name="context"></param>
    public void GetOprTypeComboList(HttpContext context)
    {
        StringBuilder sb = new StringBuilder();
        
        foreach (System.Collections.DictionaryEntry de in OperationType.OperationTypeComboList())
        {
            sb.Append("{");
            sb.AppendFormat("txt:'{0}',val:'{1}'", de.Value, de.Key);
            sb.Append("},");
        }
        if (sb.Length > 0)
        {
            sb.Remove(sb.Length - 1, 1);
        }
        context.Response.Write(string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", sb.ToString()));
        //context.Response.Write(retExecResult(Constants.ExecResult.Succ, "", sb.ToString()));
    }
    
}